package com.Ele_Demo.jackiez;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.Ele_Demo.jackiez.db.DBOpenHelper;
import com.Ele_Demo.jackiez.util.LogUtil;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Tab1 extends Activity implements OnClickListener{
	private DBOpenHelper mOpenHelper;
	public static final int DIALOG_UPLOAD_PROGRESS = 0;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 1;
	private ProgressDialog mProgressDialog;
    String uriAPI = "http://android.wuliu800.com/dbcount.php";
    //private TextView records_message;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//String status = GetStatus();
		String[] status = GetStatus().split("#");
		String user_message = "You have "+status[0]+" recods.\n The last time record is in "+status[1]+".";
        LogUtil.LogShow("[Tab1]", user_message, LogUtil.DEBUG);
        //records_message = (TextView)findViewById(R.id.text);
		setContentView(R.layout.tab1);
		((TextView)this.findViewById(R.id.text)).setText(user_message);
		Button btn_upload = (Button)findViewById(R.id.uploadbutton);
        btn_upload.setOnClickListener(this);

	}

	public String GetStatus(){
		String status = "";
		SharedPreferences passwdfile = getSharedPreferences( "USERPATH", 0);
		String path = passwdfile.getString("USERPATH", null);
		try{
	        DefaultHttpClient httpclient = new DefaultHttpClient();
	        HttpResponse response;
	        HttpPost httpost = new HttpPost(uriAPI);
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	        nvps.add(new BasicNameValuePair("username", path)); 
	        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));        
	        response = httpclient.execute(httpost);
	        HttpEntity entity = response.getEntity();
	        status = EntityUtils.toString(entity);
	        LogUtil.LogShow("[Tab1]", status, LogUtil.DEBUG);
		}
		catch(Exception e){
	        e.printStackTrace();
		}
		return status;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		BeginToUpload();
	}
	
	public void BeginToUpload(){		
		starttoexport();
		starttoupload();
	}
	
	
	public void starttoexport(){
		int contacts_account = 0;
        Button btn_upload = (Button)findViewById(R.id.uploadbutton);
		mOpenHelper = new DBOpenHelper(btn_upload.getContext());
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();	
        ContentResolver cr = getContentResolver();
		//LogUtil.LogShow("[Tab1]", "111", LogUtil.DEBUG);
		Exporter exporter = new Exporter();
		contacts_account = exporter.ExportContacts(db,cr);
        GetOtherMes(contacts_account,db);
	}
	
	
    public void starttoupload(){
        new UploadFileAsync().execute();
    }
    
    class UploadFileAsync extends AsyncTask< String, String, String> {
		
    	@Override
    	protected void onPreExecute() {
    		super.onPreExecute();
    		showDialog(DIALOG_UPLOAD_PROGRESS);
    	}
    	
    	
    	
    	@Override
    	protected String doInBackground(String... aurl) {
    		SharedPreferences passwdfile = getSharedPreferences( "USERPATH", 0);
    		String path = passwdfile.getString("USERPATH", null);
    		LogUtil.LogShow("[Tab1]", "The Path is "+path, LogUtil.DEBUG);
    		Uploader uploader = new Uploader();
    		uploader.UploadContacts(path);
    		return null;
    	}

    	@Override
    	protected void onProgressUpdate(String... progress) {
    		Log.d("ANDRO_ASYNC",progress[0]);
    		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    		}

    		 
    	@Override
    	protected void onPostExecute(String unused) {
    		dismissDialog(DIALOG_UPLOAD_PROGRESS);
    		}
    	}
    @Override
    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_UPLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Uploading file..");
    //mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    case DIALOG_DOWNLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Downloading file..");
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    default:
    return null;
    }
    }
    
    public void GetOtherMes(int contacts_account,SQLiteDatabase db){
        String sql_insert;
        int account = contacts_account;
    	TelephonyManager phoneMgr=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
		//LogUtil.LogShow("[Ele_Demo]", phoneMgr.getLine1Number(), LogUtil.DEBUG);
		//LogUtil.LogShow("[Ele_Demo]", Build.VERSION.SDK, LogUtil.DEBUG);
        sql_insert = "INSERT INTO uploadmessage(contacts_account,phone_model,version_sdk,version_os,upload_time) VALUES ('"+account+"','"+Build.MODEL+"','"
        +Build.VERSION.SDK+"','"+Build.VERSION.RELEASE+"',date('now'));";
		//LogUtil.LogShow("[test]", sql_insert, LogUtil.DEBUG);
        try {
            db.execSQL(sql_insert);
        } catch (SQLException e) {
    		LogUtil.LogShow("[test]", e.toString(), LogUtil.DEBUG);
        }
    }
}
